import { defineComponent, onMounted, reactive, ref } from "vue";
import LPopup from "@/components/public/lPopup/lPopup";
import styles from "./Detail.module.less";
import BigPreview from "@/components/public/big-preview/big-preview";
import { message, Modal } from 'ant-design-vue';
import { timestamp } from "@vueuse/core";
export default defineComponent({
  props: {
    service: {
      type: Object,
      required: true,
    },
  },
  emits: ['finishApprove'],
  setup(props, { expose, emit }) {
    let tableRender: any = null;
    const lPopupRef = ref(null as any);
    const lPopupSupplyRef = ref(null as any);
    const state = reactive({
      id: '',
      type: '',
      supply_list: [],
    } as any);
    const info = reactive({
      insurer: {
        insurer_name: '',
        insurer_idno: '',
      },
      bank: {
        benefiter_name: '',
        card_no: '',
        bank: '',
        open_bank: '',
      },
      file_status: 0,
      file_list: [],
      remark: '',
      supply_list: [],
      log: [],
    })
    const getTempFileList = (id: number | string) => {
      props.service.getTempFileList({ id }).then((res: any) => {
        state.supply_list = res?.data || [];
      })
    }
    // 打开弹窗
    const open = (id: number | string, type: string = 'detail') => {
      state.id = id;
      state.type = type;
      tableRender = message.loading('加载中', 0);
      getTempFileList(id);
      props.service.detail({ id }).then((res: any) => {
        let obj = res.data || {};
        info.insurer.insurer_name = obj.insurer_name || '';
        info.insurer.insurer_idno = obj.insurer_idno || '';
        info.bank.benefiter_name = obj.benefiter_name || '';
        info.bank.card_no = obj.card_no || '';
        info.bank.bank = obj.bank || '';
        info.bank.open_bank = obj.open_bank || '';
        info.file_status = obj.file_status || 0;
        info.file_list = obj.file_list || [];
        info.log = obj.log || [];
        lPopupRef.value.open();
      }).finally(() => {
        tableRender();
      })
    }
    // 关闭弹窗
    const closed = () => {
      state.id = '';
      state.type = '';
      info.insurer.insurer_name = '';
      info.insurer.insurer_idno = '';
      info.bank.benefiter_name = '';
      info.bank.card_no = '';
      info.bank.bank = '';
      info.bank.open_bank = '';
      info.file_status = 0;
      info.file_list = [];
      info.remark = '';
    }
    expose({
      open,
    })
    // 被保人信息
    const Insured = () => (
      <div class={styles.part}>
        <div class={styles['part-title']}>被保人信息</div>
        <div class={styles['part-rows']}>
          <div class={styles['part-row']}>
            <div class={styles['part-col']}>
              <span class={styles['part-col-label']}>姓名:</span>
              <span class={styles['part-col-value']}>{info.insurer.insurer_name}</span>
            </div>
            <div class={styles['part-col']}>
              <span class={styles['part-col-label']}>身份证号:</span>
              <span class={styles['part-col-value']}>{info.insurer.insurer_idno}</span>
            </div>
          </div>
        </div>
      </div>
    )
    // 银行卡信息
    const Bank = () => (
      <div class={styles.part}>
        <div class={styles['part-title']}>银行卡信息</div>
        <div class={styles['part-rows']}>
          <div class={styles['part-row']}>
            <div class={styles['part-col']}>
              <span class={styles['part-col-label']}>持卡人姓名:</span>
              <span class={styles['part-col-value']}>{info.bank.benefiter_name}</span>
            </div>
            <div class={styles['part-col']}>
              <span class={styles['part-col-label']}>卡号:</span>
              <span class={styles['part-col-value']}>{info.bank.card_no}</span>
            </div>
          </div>
          <div class={styles['part-row']}>
            <div class={styles['part-col']}>
              <span class={styles['part-col-label']}>银行:</span>
              <span class={styles['part-col-value']}>{info.bank.bank}</span>
            </div>
            <div class={styles['part-col']}>
              <span class={styles['part-col-label']}>开户行:</span>
              <span class={styles['part-col-value']}>{info.bank.open_bank}</span>
            </div>
          </div>
        </div>
      </div>
    )
    const downloadFile = () => {
      props.service.downloadFile({ id: state.id }).then((res: any) => {
        window.open(
          `${res.data.zip_url}`,
          "_blank"
        );
      })
    }
    const Credential = () => (
      <div class={styles.part}>
        <div class={styles['part-title']}>
          <span>单证信息</span>
          <a-button style={{ marginLeft: '10px' }} type="primary" size="small" v-show={state.type === 'detail' && info.file_status === 30} onClick={() => { downloadFile() }}>打包下载</a-button>
        </div>
        {
          info.file_list.length > 0 ? (
            <div class={styles['img-corridor']}>
              <a-image-preview-group>
                {
                  info.file_list.map((item: any, index: number) => (
                    <div class={styles['img-corridor-item']} key={item.img_url}>
                      <div class={styles['img-box']}>
                        <a-image src={item.file_url} />
                      </div>
                      <span>{item.file_name}</span>
                    </div>
                  ))
                }
              </a-image-preview-group>
            </div>
          ) : (
            <a-empty v-slots={{
              description: () => <span>暂无图片</span>
            }} />
          )
        }
      </div>
    )
    // 时间格式化
    const formatDate = (timestamp: number) => {
      const nDate = new Date(timestamp * 1000)
      const year = nDate.getFullYear();
      const month = String(nDate.getMonth() + 1).padStart(2, "0");
      const date = String(nDate.getDate()).padStart(2, "0");
      const hour = String(nDate.getHours()).padStart(2, '0');
      const minute = String(nDate.getMinutes()).padStart(2, '0');
      const second = String(nDate.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${date} ${hour}:${minute}:${second}`;
    }
    // 进度
    const TimeLine = () => (
      <div class={styles.part}>
        <div class={styles['part-title']}>进度</div>
        <div class={styles.timeline}>
          <a-timeline>
            {
              info.log.map((item: any) => (
                <a-timeline-item>{item.content + ' ' + formatDate(item.create_time)}</a-timeline-item>
              ))
            }
          </a-timeline>
        </div>
      </div>
    )
    // 补充资料
    const Remark = () => (
      <div class={styles.part}>
        <div class={styles['part-title']}>
          <span>审核内容</span>
        </div>
        <a-textarea style={{ margin: '12px 0' }} v-model:value={info.remark} placeholder="请输入审核内容" />
      </div>
    )
    // 补充资料
    const doSupply = () => {
      lPopupSupplyRef.value.open();
    }
    // 补充资料回传
    const doSupplyCallback = () => {
      doCheck(15, info.supply_list);
    }
    const doCheck = (status: number, need_files?: number[]) => {
      let modalContent = '确认提交';
      switch (status) {
        case 10:
          modalContent = '确认拒绝';
          break;
        case 15:
          modalContent = '确认需补充资料';
          break;
        case 30:
          modalContent = '确认通过';
          break;
      }
      Modal.confirm({
        title: '提交',
        content: modalContent,
        onOk: () => {
          props.service.doCheck({
            id: state.id,
            status,
            need_files,
            remark: info.remark,
          }).then((res: any) => {
            message.success('提交完成!');
            lPopupSupplyRef.value.close();
            lPopupRef.value.close();
            emit('finishApprove');
          })
        }
      })
    }
    // 底部操作栏
    const Footer = () => (
      <div class={styles.footer}>
        <a-button type="primary" onClick={() => { doCheck(30) }}>通过</a-button>
        <a-button type="primary" class="et-btn-danger" onClick={() => { doCheck(10) }}>拒绝</a-button>
        <a-button type="primary" class="et-btn-warning" onClick={() => { doSupply() }}>补充资料</a-button>
        <a-button onClick={() => { lPopupRef.value.close() }}>关闭</a-button>
      </div>
    )
    const BigPreviewRef = ref(null as any);
    return () => (
      <>
        <LPopup title="理赔详情" ref={lPopupRef} onClosed={() => closed()}>
          <div class={styles.detail}>
            <Insured />
            <Bank />
            <Credential />
            <TimeLine />
            {state.type === 'approve' && (
              <>
                <Remark />
                <Footer />
              </>
            )}
          </div>
        </LPopup>
        <LPopup title="补充资料" ref={lPopupSupplyRef} onClosed={() => {
          info.supply_list.splice(0, info.supply_list.length);
        }}>
          <div class={styles.supply}>
            <a-select v-model:value={info.supply_list} style={{ width: '100%' }} fieldNames={{ label: "name", value: "name" }} options={state.supply_list} mode="multiple" placeholder="请选择补充资料"></a-select>
            <div class={styles.footer}>
              <a-button type="primary" onClick={() => { doSupplyCallback() }}>确定</a-button>
              <a-button onClick={() => { lPopupSupplyRef.value.close() }}>关闭</a-button>
            </div>
          </div>
        </LPopup>
        <BigPreview ref={BigPreviewRef} />
      </>
    )
  }
})